package org.summerframework.component.security.context;

import org.summerframework.component.security.LoginData;
import org.summerframework.component.security.Constants;
import org.summerframework.core.util.IpUtil;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This factory class is used to create <code>RequestContext</code>, it is
 * implemented as singleton object. API client can obtain a thread-safe
 * <code>RequestContext</code> object.
 *
 * @author 石超
 * @version v1.0.0
 */
public final class RequestContextFactory {

    public static void initRequestContext(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {
        if (getLoginData() != null) {
            return;
        }
        RequestContext<LoginData> context = new RequestContext<LoginData>();
        context.setRequest(request);
        context.setResponse(response);
        context.setServletContext(servletContext);
        context.setSession(request.getSession(true));

        if (context.getSession() != null) {
            String ip = IpUtil.getIpAddr(request);
            context.setLoginData((LoginData) context.getSession().getAttribute(Constants.SESSION_LOGIN_DATE), LoginData.class);

            context.setRequestIp(ip);
            context.getLoginData().setUserAgent(request.getHeader(Constants.USER_AGENT));
            context.getSession().setAttribute(Constants.REQUEST_IP, ip);
        }

    }

    public static <T> RequestContext<T> getCurrentContext() {
        return RequestContext.getContext();
    }

    public static void clean() {
        RequestContext.clean();
    }

    public static <T> LoginData<T> getLoginData() {
        return RequestContext.<T>getContext().getLoginData();
    }

    public static LoginData getLoginData(boolean flag) {
        return RequestContext.<LoginData>getContext().getLoginData(LoginData.class);
    }
}
